package com.company.test29;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by v on 16-11-25.
 */
public class Test2907 {
    private static Account account=new Account();
    private static  int balance=0;
    private static Lock lock=new ReentrantLock(false);
    private static Lock lock2=new ReentrantLock(false);

    private static class Account{

        public int getBalance(){
            return balance;
        }

        public void deposit(int amount){
            lock.lock();
            //System.out.print("ininin ");
            int newBalance=balance+amount;
            System.out.print(amount);
            try {
                Thread.sleep(5);
                balance=newBalance;
            }catch (InterruptedException ex){

            }finally {
                //lock.unlock();
            }
        }
    }

    private static class AddBalance implements Runnable{
        int amount;

        public AddBalance(int amount){
            this.amount=amount;
        }

        @Override
        public void run() {
            lock2.lock();
            balance++;
            System.out.println(amount);
            //lock.unlock();
        }
    }

    private static class AddAPennyTask implements Runnable{
        int amount;

        public AddAPennyTask(int amount){
            this.amount=amount;
        }

        @Override
        public void run() {
            account.deposit(amount);
            System.out.println("gogogo");
        }
    }

    public static void main(String[] args) {
        ExecutorService executor= Executors.newFixedThreadPool(190);

        for(int i=0;i<95;i++){
            executor.execute(new AddAPennyTask(i));
            //System.out.println(Account.balance);
        }


        for(int i=0;i<100;i++){
            executor.execute(new AddBalance(i));
        }

        for(int i=0;i<5;i++){
            executor.execute(new AddAPennyTask(i));
        }

        executor.shutdown();

        while (!executor.isTerminated()){
            //System.out.println(balance++);
        }

        System.out.println("What is balance? "+account.getBalance());
    }
}
